<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Http;
use fast\Random;
use think\Config;
use think\Db;
use think\Request;
use think\Exception;
use think\Validate;
use app\common\model\User as UserModel;
use app\common\model\Article;
use app\common\model\Comment;
use app\common\library\Upload;
/**
 * 用户接口
 */
class User extends Api
{
    protected $noNeedLogin = ['wxlogin','get_asd','center'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 微信登录
     *
     * @ApiMethod (POST)
     */
    public function wxlogin()
    {
        $code = $this->request->post("code"); //用户code
        $nickname = $this->request->post("nickname",'', 'trim');//用户昵称
        $avatar = $this->request->post("avatar",'', 'trim');//头像
//        $avatar='https://thirdwx.qlogo.cn/mmopen/vi_32/DYAIOgq83er3Kf8a0otT1icbM0Epiac0TscUSMTB5XZe9pjBrojxhMlNZoU7ObHlwdI39rL95fD7eZswS8CTGZicQ/132';
//        $code='1111';
//        $nickname='180斤的肥宅';

        if(!$code)
        {
            $this->error('code无效');
        }
        if(!$nickname || !$avatar){
            $this->error('用户信息错误！');
        }
        $params = [
            'appid'      => Config::get('site.appid'),
            'secret'     => Config::get('site.secret'),
            'js_code'    => $code,
            'grant_type' => 'authorization_code'
        ];
        $result = Http::sendRequest("https://api.weixin.qq.com/sns/jscode2session", $params, 'GET');

        if ($result['ret']) {
            $json = (array)json_decode($result['msg'], true);
            if (isset($json['openid'])) {
                //openid 查找用户是否存在
                $auth = \app\common\library\Auth::instance();
                $user = UserModel::getByOpenid($json['openid']);
                if(!$user){
                    $insert_data = [];
                    $insert_data['nickname']= $nickname;
                    $insert_data['username']= $nickname;
                    $insert_data['avatar']= $avatar;
                    $insert_data['openid']=  $json['openid'];
                    $insert_data['access_token']=  $json['session_key'];
                    $insert_data['createtime']=  time();
                    $insert_data['status'] = 'normal';
                    $insert_data['logintime'] = time();
                    $insert_data['prevtime'] = time();
                    $insert_data['jointime'] = time();
                    $insert_data['joinip'] =request()->ip();
                    //注册账号
                    Db::startTrans();
                    try {
                        $uid = UserModel::insertGetId($insert_data);
                        Db::commit();
                    }catch (\Exception $e){
                        Db::rollback();
                        $this->error('授权失败');
                    }

                }else{
                    //登录账号
//                    $user->nickname=$nickname;
//                    $user->avatar=$avatar;
//                    $user->save();
                    $user->prevtime = $user->logintime;
                    //记录本次登录的IP和时间
                    $user->logintime = time();
                    $user->joinip =request()->ip();
                    $user->save();
                    $uid= $user->id;
                }
                $jwt= new \app\common\library\JwtToken();
                $token = $jwt->setJwtToken($uid);
                $this->success('登录成功',['token'=>$token],200);
            }
        }
        $this->error('授权失败');
    }



    /**
     * 个人中心页面
     */
    public function center()
    {
        $uid = $this->auth->id;
        if(!$uid){$this->success('未登录状态没有数据',[],-101);}
        $art_ids = 0;
        $collects = 0;
        $likes = 0;
        $like_collect =0;
        //获取用户的数据;
        $user_model = new \app\common\model\User();
        $user_info = $user_model->field('id,avatar,nickname,bio')->where('id',$uid)->find();
        if(!$user_info){
            $this->error('用户已被删除');
        }
        //粉丝
        $follow_model =new Follow();
        $fans = $follow_model->myFanNum(1)?$follow_model->myFanNum(1):0;
        //赞与收藏
        $article_model = new \app\common\model\Article();
        $list = $article_model->field('sum(likes) likes,sum(collects) collects,count(id) artids,user_id')->where('user_id',$uid)->group('user_id')->find();
        $info = json_decode(json_encode($list),true);
        //发布的笔记数 获得点赞数  获得收藏数
        if($info){
            if(isset($info['collects']) && $info['collects']){$collects=$info['collects'];}
            if(isset($info['likes']) && $info['likes']){$likes=$info['likes'];}
            if(isset($info['artids']) && $info['artids']){$art_ids=$info['artids'];}
        }
        $like_collect = (int)$likes + (int)$collects;
        //关注
        $follows = $follow_model->myFollowNum(1)?$follow_model->myFollowNum(1):0;
        $user_info->fans=$fans;
        $user_info->follows=$follows;
        $user_info->like_collect=$like_collect;
        $user_info->art_ids=$art_ids;
        $user_info->collects=$collects;
        $user_info->likes=$likes;
        $preg = "/^http(s)?:\\/\\/.+/";
        if(!preg_match($preg,$user_info->avatar)){
            $user_info->avatar=cdnurl($user_info->avatar, true);
        }
        $this->success('获取成功',$user_info,200);
    }
    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('退出成功'));
    }

    /**
     * 上传头像
     */
    public function upload()
    {
        Config::set('default_return_type', 'json');
        //必须设定cdnurl为空,否则cdnurl函数计算错误
        Config::set('upload.cdnurl', '');
        $uid = $this->auth->id;
        $user_model=new \app\common\model\User();
        $user=$user_model->field('id,avatar,nickname,birthday,gender,bio')->where('id',$uid)->find();
        if(!$user){
            $this->error('用户不存在');
        }
        $attachment = null;
        //默认普通上传文件
        $file = $this->request->file('file');
        try {
            $upload = new Upload($file);
            $attachment = $upload->upload();
        } catch (UploadException $e) {
            $this->error($e->getMessage());
        }
        $user->where('id',$uid)->update(['avatar'=>cdnurl($attachment->url, true)]);
//            $this->success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
        $this->success(__('Uploaded successful'), ['url' =>cdnurl($attachment->url, true)]);

    }
    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     */
    public function profile()
    {
        $uid = $this->auth->id;
        $user_model=new \app\common\model\User();
        $user=$user_model->field('id,avatar,nickname,birthday,gender,bio')->where('id',$uid)->find();
        if(!$user){
            $this->error('用户不存在');
        }
        $url = $user->avatar;
        $preg = "/^http(s)?:\\/\\/.+/";
        if(!preg_match($preg,$url)){
            $user->avatar=cdnurl($url, true);
        }
        if($this->request->method() == "POST"){
            //获取保存的类型 1:昵称 2：性别 3：生日 4：个人简介
            $type = $this->request->post('type');
            if(!$type){
                $this->error('参数错误');
            }
            switch ($type){
                case 1:
                    $nickname = $this->request->post('nickname','trim,htmlspecialchars');
                    if(!$nickname){
                        $this->error('请填写昵称');
                    }
                    $user->nickname = $nickname;
                    break;
                case 2:
                    $gender = $this->request->post('gender/d');
                    $user->gender = $gender;
                    break;
                case 3:
                    $birthday = $this->request->post('birthday');
                    $user->birthday = $birthday;
//                    if($birthday){
//                        $user->birthday = date('Y-m-d',$birthday);
//                    }
                    break;
                case 4:
                    $bio = $this->request->post('bio','trim,htmlspecialchars');
                    $user->bio = $bio;
                    break;
                default:
                    $this->error('参数错误');
                    break;
            }
            $user->save();
            $this->success('保存成功','',200);
        }
        $this->success('获取成功',$user,200);
    }

    /**
     * 发布评论
     */
    public function comment()
    {
        $uid=$this->auth->id;
        if(!$uid){$this->error('请先登录');}
        if($this->request->method()=="POST"){
            $aid = $this->request->post('aid',0);//文章的id
            $id = $this->request->post('id',0);//评论id 默认0
            $content = $this->request->post('content','');//内容
            //评论 1：顶级 2：二级 回复评论
            $type = $this->request->post('type',1);//1 是对文章的评论  2：对评论的评论或回复
            if(!$content){
                $this->error('请填写内容');
            }
            if(preg_match_all('/./us', $content, $match)>200){
                $this->error('最多可以评论200个汉字');
            }
            $top_id = $this->request->post('top_id',0);//获取到顶级评论id  默认是对文章评论
            $to_user_id = $this->request->post('to_user_id',0);// 被回复人的user_id
            $articleModel = new \app\common\model\Article();

            $art_list = $articleModel->getById($aid);
            if(!$art_list){
                $this->error('文章未查询到',$art_list);
            }
            //文章的评论
            $comment_model=new \app\common\model\Comment();
            $pid_info = $comment_model->where('id',$id)->find();
            $pid_info=json_decode(json_encode($pid_info),true);
            $show_reply = 0;
            if($type==2){
                if($pid_info){
                    if($pid_info['pid'] != 0){
                        $show_reply=1;
                    }
                }
            }

            $data = [
                'aid'=>$aid,
                'content'=>$content,
                'user_id'=>$uid,
                'to_user_id'=>$to_user_id,
                'pid'=>$id,
                'level'=>$type,
                'top_id'=>$top_id,
                'show_reply'=>$show_reply,
                'createtime'=>time()
            ];
            $comment_id = $comment_model->insertGetId($data);
            $where['c.id'] = $comment_id;
            $articleModel->where('id',$aid)->setInc('comments');
            $content_info= $comment_model->getOne($where);
            $this->success('评论成功',$content_info,200);
        }
        $this->error('请求失败');
    }

    /**
     * 发布评论
     */
    public function comment2()
    {
        $uid=$this->auth->id;
        if(!$uid){$this->error('请先登录');}
        if($this->request->method()=="POST"){
            $aid = $this->request->post('aid',0);//文章的id
            $content = $this->request->post('content','');
            //评论 1：顶级 2：二级 回复评论
            $type = $this->request->post('type','');
            if(!$content){
                $this->error('请填写内容');
            }
            $this->model=null;
            $articleModel = new \app\common\model\Article();
            $art_list = $articleModel->getById($aid);
            if(!$art_list){
                $this->error('文章未查询到',$art_list);
            }
            //文章的评论
            if($type == 1){
                $this->model=new \app\common\model\Comment();
                $data = [
                    'aid'=>$aid,
                    'content'=>$content,
                    'user_id'=>$uid,
                    'createtime'=>time()
                ];
            }else{
                //回复
                $this->model=new \app\common\model\Reply();
                //flag 是 1 是二级评论  2是回复
                $flag = $this->request->post('flag');
                //回复此条评论的id
                $id = $this->request->post('id');
                //根评论的id
                $comment_id =$this->request->post('comment_id',$id);
                //回复的人
                $to_uid = $this->request->post('to_uid');
                if(!$flag || !$comment_id || !$id || !$to_uid){
                    $this->error('缺少评论参数');
                }
                $data = [
                    'aid'=>$aid,
                    'content'=>$content,
                    'from_uid'=>$uid,
                    'comment_id'=>$comment_id,
                    'pid'=>$id,
                    'to_uid'=>$to_uid,
                    'flag'=>$flag,
                    'createtime'=>time()
                ];
            }

            $comment_id = $this->model->insertGetId($data);
            $where['c.id'] = $comment_id;
            $content_info= $this->model->getOne($where);
            $this->success('评论成功',$content_info,200);
        }
        $this->error('请求失败');
    }

    /**
     * 我的评论
     */
    public function my_comment()
    {
        // 查出用户所有发表的文章
        $where=[];
        //本人
        $art_ids = \app\common\model\Article::where(['user_id'=>$this->auth->id])->column('id');
        //查出所有的对本人文章的评论
        $comment_info = \app\common\model\Comment::where(['aid'=>['in',$art_ids]])->select();
        $comment_info = collection($comment_info)->toArray();

        //查出所有的2级评论和2回复
        $reply_model = new \app\common\model\Reply();
        $reply_list = $reply_model->where('to_uid',$this->auth->id)->select();
        $reply_list = collection($reply_list)->toArray();
        if($reply_list){
            foreach ($reply_list as &$v){
                if($v['flag']){
                    //对本人的回复
                }else{}

            }
        }

        $page=1;
        $limit = 2;
        $total = db("comment")->count();
        if($data){
            $data =  page_array($limit,$page,$data,1);
        }
        $this->success('横杠',['current_page'=>$page,'data'=>$data]);
    }

    /**
     * 回复接口
     */
    public function reply()
    {
        //$id
        $uid=$this->auth->id;
        if(!$uid){$this->error('请先登录');}
        if($this->request->method()=="POST"){
            $comment_id = $this->request->post('id');//一级评论的id
            //flag 是0二级评论 1：回复
            $flag = $this->request->post('flag',0);//默认二级平路
            $aid = $this->request->post('aid',0);//文章的id
        }
    }
    /**
     * 我的文章列表
     */
    public function article_list(){
        $articleModel = new \app\common\model\Article();
        $list = $articleModel->getList(['user_id'=>$this->auth->id],true);
        $this->success('获取成功',$list,200);
    }

    //收藏点赞 自己发表的文章
    public function get_asd()
    {
        $articleModel = new \app\common\model\Article();
        $type = $this->request->param('type',1);
        $uid = $this->auth->id;
        if(!$uid){
            $this->success('获取成功',[],200);
        }
        $list = $articleModel->getTypeList($type,$uid);
        $this->success('获取成功',$list,200);
    }
    /**
     * 发布文章
     */
    public function archives_post()
    {
        // 如果来源于提交
        $row = $this->request->post('', '', 'trim,xss_clean');
        if($row['is_draft']){
            $model= new \app\common\model\Draft();
        }else{
            $model = new \app\common\model\Article();
            $rule = [
                'title|标题'      => 'require|length:3,30',
            ];

            $msg = [
                'title.require'   => '标题不能为空',
                'title.length'    => '标题长度限制在3~30个字符',
                'content.require' => '内容不能为空',
            ];
            $validate = new Validate($rule, $msg);
            $result = $validate->check($row);

            if (!$result) {
                $this->error($validate->getError());
            }
            if(!isset($row['content'])){
                $this->error('请上传内容');
            }
            if(preg_match_all('/./us', $row['content'], $match)>500){
                $this->error('内容长度限制在500个汉字');
            }
            if(!isset($row['file_type'])){
                $this->error('请上传图片或视频');
            }
            if($row['file_type'] ==1 && !$row['images']){
                $this->error('请上传图片或视频');
            }
            if($row['file_type'] ==2 && !$row['video']){
                $this->error('请上传图片或视频');
            }
        }
        $row['user_id'] = $this->auth->id;
        $row['createtime'] = time();
        $row['type'] = 2;
        //编辑的时候
        Db::startTrans();
        try {
            if(isset($row['id'])){
                $model->allowField(true)->isUpdate(true)->save($row);
            }else{
                $model->allowField(true)->save($row);
            }

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error("发生错误:" . $e->getMessage());
        }
        $this->success("发布成功！");
    }


    /**
     * 草稿
     */
    public function save_draft()
    {
        // 如果来源于提交
        $draft_model = new \app\common\model\Draft();
        $uid = $this->auth->id;
        $info = $draft_model->where('user_id',$uid)->order('createtime desc')->find();
//        if($this->request->method()=="POST"){
//            $row = $this->request->post('', '', 'trim,xss_clean');
//            if(isset($row['content'])){
//                if(preg_match_all('/./us', $row['content'], $match)>500){
//                    $this->error('内容长度限制在500个汉字');
//                }
//            }
//            $row['user_id'] = $this->auth->id;
//            $row['createtime'] = time();
//            $row['type'] = 2;
//            //编辑的时候
//            Db::startTrans();
//            try {
//                $draft_model->allowField(true)->save($row);
//                Db::commit();
//            } catch (\Exception $e) {
//                Db::rollback();
//                $this->error("发生错误:" . $e->getMessage());
//            }
//            $this->success("保存成功！");
//        }
        if($info){
            if($info->images){
                $images = explode(',',$info->images);
                foreach ($images as &$v){
                    $v= cdnurl($v,true);
                }
                $info->images=$images;
            }
            if($info->video){
                $info->video= cdnurl($info->video,true);
            }
            if($info->cover){
                $info->cover = cdnurl($info->cover,true);
            }
        }
        $this->success('获取成功',$info);
    }

    //获取到推荐的人
    public function referrer()
    {
        //获取我关注的人
        $Follow_model=new Follow();
        $follow_info=[];
        $uid = $this->auth->id;
        $follow_info = $Follow_model->myFollowList(1,$uid);
        array_push($follow_info,$uid);//获取到所有的
        $referrer_model = new \app\common\model\Referrer();
        $remove = $referrer_model->where('uid',$uid)->column('other');
        if($remove){
            $follow_info = array_merge($follow_info,$remove);
        }
        //发表文章最多的
        $where['u.id']= array('not in',$follow_info);
//        $where['a.type']= 2;//用户
//        $info = \app\common\model\Article
//            ::alias('a')
//            ->where($where)
//            ->field('sum(a.likes) as likes,a.user_id,u.avatar,u.nickname')
//            ->join('user u','a.user_id=u.id')
//            ->group('a.user_id')
//            ->order('a.likes desc')
//            ->select();
        $info = \app\common\model\User
            ::alias('u')
            ->field('u.id user_id,u.avatar,u.nickname')
            ->where($where)
//            ->with('article')
            ->select();
        $info = json_decode(json_encode($info),true);
        $this->success('获取成功',$info,200);
    }

    //移除推荐的人
    public function remove_refer()
    {
        $other= $this->request->get('user_id');//不再推荐的人
        $uid = $this->auth->id;//自己
        if(!$other){
            $this->error('参数错误');
        }
        $other_info = db("user")->where('id',$other)->find();
        if(!$other_info){
            $this->error('用户不存在');
        }
        $referrer_model = new \app\common\model\Referrer();
        $where= [];
        $where['uid']=$uid;
        $where['other']=$other;
        $info = $referrer_model->where($where)->find();
        if(!$info){
            $data['other'] = $other;
            $data['uid'] = $uid;
            $referrer_model->save($where);
        }
        $this->success('操作成功','',200);
    }
    //删除评论
    public function del_comment()
    {
        $comment_id = $this->request->get('id');//删除的评论id
        if(!$comment_id){
            $this->error('缺少参数');
        }
        $uid = $this->auth->id;
        $info = db('user')->where('id',$uid)->find();
        if(!$info){
            $this->error('该用户不存在');
        }
        $comment_info =  Db::name('Comment')->where(['id'=>$comment_id])->find();
        if(!$comment_info){
            $this->error('评论已删除');
        }
        if($comment_info['user_id'] !=$uid){
            $this->error('只可以删除自己的评论');
        }
        $art_info =Db::name('Article')->where('id',$comment_info['aid'])->find();
        if(!$art_info){
            $this->error('文章已删除');
        }
        $num = 1;
        if($comment_info['top_id'] == 0){
            $count = Db::name('Comment')->where(['top_id'=>$comment_id,'aid'=>$comment_info['aid']])->count();
            $num+=$count;
        }
        $free =$art_info['comments']-$num;
        Db::startTrans();
        try {
            if($comment_info['top_id'] == 0){
                Db::name('Comment')->where(['top_id'=>$comment_id,'aid'=>$comment_info['aid']])->delete();
            }
            Db::name('Comment')->where(['id'=>$comment_id,'user_id'=>$uid,'aid'=>$comment_info['aid']])->delete();
            Db::name('Article')->where('id',$comment_info['aid'])->update(['comments'=>$free]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error("删除失败");
        }
        $this->success('删除成功',$free);
    }
}
